import org.springframework.web.servlet.support.RequestContextUtils as RCU
import org.springframework.web.context.request.RequestContextHolder as RCH


/**
 * Thumbnailing image service which uses imageMagick
 */

class ImageService {
   boolean transactional = false

        
      /**
       * upload process
       */
	def thumbnail( multiPartFile, thumbnailFileName, grailsApplication) {
		def baseWebPath = RCH.requestAttributes.servletContext.getRealPath('/')


		def imPath = grailsApplication.config.gk.imageMagickPath
		def tnQuality = grailsApplication.config.gk.thumbnail.quality
		def tnX = grailsApplication.config.gk.thumbnail.x
		def tnY = grailsApplication.config.gk.thumbnail.y

		if(!multiPartFile?.empty) { 
			def pathAndFileOrig = baseWebPath + 'images/uploaded/' + multiPartFile.getOriginalFilename()
			def pathAndFileFinal = baseWebPath + 'images/uploaded/' + thumbnailFileName
			def pathAndFileThumb= baseWebPath + 'images/thumbs/' + thumbnailFileName
			multiPartFile.transferTo(new File(pathAndFileOrig) )
			if(imPath!='') { 
				def thumbNailCommand = imPath + " -quality " + tnQuality
				thumbNailCommand += " -scale " + tnX + "x" + tnY + " " 
				thumbNailCommand += pathAndFileOrig
				thumbNailCommand += " " + pathAndFileThumb

// do the thumbnailing with imagemagick
				def proc = Runtime.getRuntime().exec(thumbNailCommand)	
				def status = 0
				while(true) { 
					try {
						status = proc.waitFor()
						break
					} catch (Exception e) { 
						println e
					}
				}

  				def originalCommand = imPath + " "
				originalCommand += pathAndFileOrig
				originalCommand += " " + pathAndFileFinal
println originalCommand
// do the thumbnailing with imagemagick
				def procFinal = Runtime.getRuntime().exec(originalCommand)
				def statusFinal = 0
				while(true) { 
					try {
						statusFinal = procFinal.waitFor()
						break
					} catch (Exception e) { 
						println e
					}
				}
          
            
                        } else {
// if we don't have imagemagick installed, make the original file the 
// thumbnail as well (suboptimal but won't throw any errors then)
			multiPartFile.transferTo(new File(pathAndFileThumb) )

			}
		}
      }
  
}
